package com.gcc.jwtdemo.controller;

import com.gcc.jwtdemo.model.User;
import com.gcc.jwtdemo.repository.UserRepository;
import com.gcc.jwtdemo.service.MyUserDetailsService;
import com.gcc.jwtdemo.util.JwtUtil;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private MyUserDetailsService myUserDetailsService;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtil jwtUtil;

    // 注册接口
    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setRole("ROLE_USER"); // 默认角色
        userRepository.save(user);
        return ResponseEntity.ok("User registered successfully!");
    }

    // 登录接口，返回 JWT
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody User user) {
        Authentication authentication = authenticationManager.authenticate( // 【修改】获取 Authentication 对象
                new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword())
        );
        // 【修改】直接将 Authentication 对象传递给 generateToken
        final String jwt = jwtUtil.generateToken(authentication);

        return ResponseEntity.ok(new AuthenticationResponse(jwt));
    }
}

@Getter
class AuthenticationResponse {
    private final String jwt;

    public AuthenticationResponse(String jwt) {
        this.jwt = jwt;
    }

}